from rest_framework import status
from rest_framework.request import Request
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_simplejwt.exceptions import TokenError, InvalidToken
from rest_framework_simplejwt.views import TokenObtainPairView



class LoginView(TokenObtainPairView):

    def post(self, request: Request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        try:
            serializer.is_valid(raise_exception=True)
        except TokenError as e:
            raise InvalidToken(e.args[0])

        user = serializer.user
        usera = {"username": user.username}
        usera.update({"abc": "abc"})
        print(type(serializer.user))
        result = serializer.validated_data
        result['username'] = serializer.user.username
        # result['avatar'] = serializer.user.get_avatar(serializer.user)
        result['avatar'] = serializer.user.avatar
        result['mobile'] = serializer.user.mobile
        result['email'] = serializer.user.email
        result['id'] = serializer.user.id
        result['is_superuser'] = serializer.user.is_superuser
        result['token'] = result.pop('access')

        return Response(result, status=status.HTTP_200_OK)




class LogoutView(APIView):
    # 去除掉全局的rbac访问权限
    permission_classes = (IsAuthenticated,)

    def post(self, request, *args, **kwargs):
        result = {
            'msg': '退出成功！',
        }
        return Response(result, status=status.HTTP_200_OK)




